Playing with CSS Variables and JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!-- HTML -->
<h2>Update CSS Variables with <span class="hl">JS</span></h2>

<div class="controls">
<label for="spacing">Spacing:</label>
<input
id="spacing"
type="range"
name="spacing"
min="10"
max="200"
value="10"
data-sizing="px"
/>

<label for="blur">Blur:</label>
<input
id="blur"
type="range"
name="blur"
min="0"
max="25"
value="0"
data-sizing="px"
/>

<label for="base">Base Color</label>
<input id="base" type="color" name="base" value="#ffc600" />
</div>

<img src="https://source.unsplash.com/7bwQXzbF6KE/800x500" />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* css */
:root {
--base: #ffc600;
--spacing: 10px;
--blur: 0px;
}

img {
padding: var(--spacing);
background: var(--base);
filter: blur(var(--blur));
}

.hl {
color: var(--base);
}

element.style.setProperty(property, value)setProperty() 메소드를 사용하여 자바스크립트에서 css커스텀 속성을 읽고 쓸 수 있습니다.

1
2
3
4
5
6
7
8
9
10
const inputs = document.querySelectorAll(".controls input");

// input range의 변화값 값 인지
function handleUpdate(e) {
const suffix = e.dataset.sizing || "";
document.documentElement.style.setProperty(`--${e.name}`,e.value + suffix);
}

inputs.forEach(input => input.addEventListener("change", handleUpdate));
inputs.forEach(input => input.addEventListener("mousemove", handleUpdate));